<template>
  <!--  搜索栏 -->
  <div class="app-container">
    <basic-search-form
      ref="vBasicSearchForm"
      style="margin-bottom: 8px"
      :columns="columns"
      inline
      size="small"
      @search="serach"
    >
      <template #businessesId="{ formdata }">
        <el-select
          v-model="formdata.businessesId"
          filterable
          placeholder="请选择"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="item in businessesList"
            :key="item.id"
            :label="item.businessesName"
            :value="item.id"
          />
        </el-select>
      </template>
      <template #status="{ formdata }">
        <el-select v-model="formdata.status" placeholder="请选择" clearable style="width: 100%">
          <el-option
            v-for="item in statusList"
            :key="item.code"
            :label="item.info"
            :value="item.code"
          />
        </el-select>
      </template>
    </basic-search-form>
    <!-- 表格 -->
    <basic-table
      ref="vBasicTable"
      :api="getWharfPageList"
      :immediate-fetch="false"
      :before-fetch="beforeFetch"
      :table-schema="tableSchema"
      :actions="tableActions"
      :table-prop="tableProp"
      :table-event="tableEvent"
      :row-info="{
        rowKey: 'data',
      }"
    >
      <template #statusStr="{ row }">
        <div style="text-align: center">
          <el-tag v-if="row.status == 1" type="success" size="small">{{ row.statusStr }}</el-tag>
          <el-tag v-if="row.status == 0" type="danger" size="small">{{ row.statusStr }}</el-tag>
        </div>
      </template>
      <!-- 表格上方按钮-->
      <template #tableHead="{ total }">
        <div>码头统计：{{ total }}个</div>
        <div style="height: 32px">
          <el-button size="mini" type="primary" @click="handleAdd">新增码头</el-button>
          <el-button size="mini" @click="handleUpdateBusinesses(null)">改归属商户</el-button>
          <el-button size="mini" @click="handleDisable(null)">批量禁用</el-button>
          <el-button size="mini" @click="handleEnable(null)">批量恢复</el-button>
          <el-button size="mini" @click="handleExport">导出EXCEL</el-button>
        </div>
      </template>
    </basic-table>
    <!--  调整归属商户弹窗  -->
    <update-businesses-dialog
      :initial-selected-wharf="selectedWharf"
      :initial-selected-wharfs="selectedWharfs"
      :businesses-list="businessesList"
      :is-visible.sync="isDialogVisible"
      @updateBusinessesCallBack="handleUpdateBusinessesCallBack"
    ></update-businesses-dialog>
  </div>
</template>

<script>
import { searchColumns, tableActions, tableSchema } from '@/views/businesses/wharf/list/modal.data';
import { download } from '@/utils/request';
import { getWharfPageList, batchUpdateStatus, deleteWharf } from '@/api/wharf';
import { getBusinessesList } from '@/api/common';
import UpdateBusinessesDialog from '@/views/businesses/wharf/list/components/UpdateBusinessesDialog.vue';

export default {
  components: { UpdateBusinessesDialog },
  data() {
    return {
      columns: searchColumns(this),
      tableSchema: tableSchema,
      tableActions: tableActions(
        this.handleDetail,
        this.handleUpdate,
        this.handleUpdateBusinesses,
        this.handleDisable,
        this.handleDelete,
      ),
      tableProp: {},
      tableEvent: {
        'selection-change': (selection) => {
          this.selectedWharfs = selection.map((item) => item.id);
        },
      },
      queryParams: {},
      businessesList: [],
      statusList: [
        { code: 1, info: '正常' },
        { code: 0, info: '已禁用' },
      ],
      isShowDialog: false,
      selectedWharf: {},
      selectedWharfs: [],
      isDialogVisible: false,
    };
  },
  mounted() {
    this.getBusinessesList();
    this.$refs.vBasicSearchForm.search();
  },
  methods: {
    getWharfPageList,
    serach(form) {
      this.queryParams = { ...form };
      this.$refs.vBasicTable.fetch();
    },
    beforeFetch() {
      return this.queryParams;
    },
    /**
     * 详情
     * @param row
     */
    handleDetail(row) {
      this.$router.push({ name: 'WharfDetail', query: { id: row.id } });
    },
    /**
     * 新增
     */
    handleAdd() {
      this.$router.push({ name: 'WharfSave' });
    },
    /**
     * 编辑
     * @param row
     */
    handleUpdate(row) {
      this.$router.push({ name: 'WharfSave', query: { id: row.id } });
    },
    handleDelete(row) {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteWharf(row.id).then(() => {
          this.$message.success('删除成功');
          this.$refs.vBasicTable.fetch();
        });
      });
    },
    handleUpdateBusinesses(wharf) {
      if (wharf === null && this.selectedWharfs.length === 0) {
        this.$message.error('请先选择一条或多个码头');
        return;
      }
      if (this.selectedWharfs.length === 0) {
        this.selectedWharf = wharf;
      }
      this.isDialogVisible = true;
    },
    handleUpdateBusinessesCallBack() {
      this.isDialogVisible = false;
      // 更新完成后的回调，比如刷新船舶列表等
      this.selectedWharf = null;
      this.selectedWharfs = [];
      this.$refs.vBasicTable.fetch();
    },

    /**
     * 获取归属商户下拉列表
     */
    getBusinessesList() {
      getBusinessesList().then((res) => {
        this.businessesList = res.data;
      });
    },
    handleDisable(row) {
      if (row === null && this.selectedWharfs.length === 0) {
        this.$message.error('请先选择一条或多个码头');
        return;
      }
      let message = '';
      if (row) {
        this.selectedWharfs = [row.id];
        message = '已选中码头：' + row.wharfName + '，';
      }
      this.$confirm(
        `${message === '' ? '已选' + this.selectedWharfs.length + '个，' : message}确定将码头禁用？禁用后码头将不展示`,
        '禁用',
        {
          confirmButtonText: '禁用',
        },
      )
        .then(async () => {
          const data = await batchUpdateStatus(this.selectedWharfs.join(','), 0);
          if (data.code === 200) {
            this.$message.success(data.msg);
            this.selectedWharfs = [];
            this.$refs.vBasicTable.fetch();
          } else {
            this.$message.error(data.msg);
          }
        })
        .catch(() => {});
    },
    handleEnable(row) {
      if (row === null && this.selectedWharfs.length === 0) {
        this.$message.error('请先选择一条或多个码头');
        return;
      }
      if (row) {
        this.selectedWharfs = [row.id];
      }
      this.$confirm(
        `${'已选' + this.selectedWharfs.length + '个，'}确定将码头恢复？恢复后码头将展示`,
        '恢复',
        {
          confirmButtonText: '恢复',
        },
      )
        .then(async () => {
          const data = await batchUpdateStatus(this.selectedWharfs.join(','), 1);
          if (data.code === 200) {
            this.$message.success(data.msg);
            this.selectedWharfs = [];
            this.$refs.vBasicTable.fetch();
          } else {
            this.$message.error(data.msg);
          }
        })
        .catch(() => {});
    },
    /**
     * 导出
     */
    handleExport() {
      download('/wharf/export', { ...this.queryParams }, `码头列表_${new Date().getTime()}.xlsx`);
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background-color: #f1f1f1;
}
</style>
